<script setup>
import { reactive, ref, onMounted } from 'vue'
import EditForm from '@/views/system/menu/Edit.vue'
import {
  menuPage,
  menuBatchDelete,
  menuRemoveById,
  updateEnableByNo,
  getSysMenuListTree
} from '@/apis/menu.js'
import { ElMessage, ElMessageBox } from 'element-plus'

let searchEntity = reactive({})
let searchForm = ref()
let searchFormItem = ref()
let more = reactive({ state: false, icon: 'CaretBottom', text: '展开' })
let editfrom = ref()
let tableData = reactive({
  current: 1,
  size: 10,
  total: 0,
  pages: 0,
  records: []
})

let selected = ref([])
function selectionChange(selection) {
  selected.value = selection
}

function handleEdit(no) {
  editfrom.value.open(no)
}

function showMore() {
  if (more.state) {
    searchFormItem.value.style.height = '52px'
    more.state = false
    more.text = '展开'
    more.icon = 'ArrowDown'
  } else {
    searchFormItem.value.style.height = '100%'
    more.state = true
    more.icon = 'ArrowUp'
    more.text = '收起'
  }
  instance.ctx.$forceUpdate()
}

function getIndex(index) {
  return (tableData.current - 1) * tableData.size + index + 1
}

function resetForm() {
  if (!searchForm) return
  searchForm.value.resetFields()
}

function getPage() {
  menuPage({
    current: tableData.current,
    size: tableData.size,
    name: searchEntity.name,
    type: searchEntity.type,
    parentNo: searchEntity.parentNo,
    permission: searchEntity.permission,
    enable: searchEntity.enable
  })
    .then((res) => {
      res.records.forEach((element, idx) => {
        element.index = (tableData.current - 1) * tableData.size + idx + 1
        element.children.forEach((child, index) => {
          child.index = element.index + '.' + (index + 1)
        })
      })

      tableData.current = res.current
      tableData.size = res.size
      tableData.total = res.total
      tableData.pages = res.pages
      tableData.records = res.records
    })
    .catch((error) => {
      console.log(error)
    })

  getListTree()
}

function batchDelete() {
  let caidan = selected.value.filter((item) => {
    return item.type == '菜单'
  }).length

  let gongneng = selected.value.filter((item) => {
    return item.type == '功能'
  }).length

  ElMessageBox.confirm(
    '确定要删除 ' + (caidan > 0 ? caidan + ' 个菜单、' : '') + gongneng + ' 个功能吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      menuBatchDelete(selected.value.map((elem) => elem.no))
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

function handleDelete(no) {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      menuRemoveById(no)
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

function handleSizeChange(size) {
  tableData.size = size
  getPage()
}

function handleCurrentChange(current) {
  tableData.current = current
  getPage()
}

function updateEnable(row, no, enable) {
  row.enable = !enable
  ElMessageBox.confirm('确定要修改当前状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      updateEnableByNo(no, enable)
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '修改成功'
            })

            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消修改'
      })

      getPage()
    })
}

let treeList = reactive({
  tree: {
    list: []
  }
})

function getListTree() {
  treeList.tree.list = []
  getSysMenuListTree()
    .then((response) => {
      response.forEach((element) => {
        let obj = {
          value: element.id,
          label: element.name,
          children: []
        }
        if (element.children != undefined && element.children.length > 0) {
          element.children.forEach((children) => {
            obj.children.push({
              value: children.id,
              label: children.name
            })
          })
        }
        treeList.tree.list.push(obj)
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

function handleAddGongNeng(no) {
  editfrom.value.openTwo(no)
}

onMounted(() => {
  getPage()
})
</script>

<template>
  <el-card class="searchForm" header="查询条件" shadow="never">
    <template #header>
      <div class="card-header">
        <el-icon style="color: rgb(12 43 77)" size="18"><Operation /></el-icon>
        <h1>查询条件</h1>
      </div>
    </template>
    <el-form inline :model="searchEntity" label-width="70px" ref="searchForm">
      <div ref="searchFormItem" style="height: 52px; overflow: hidden">
        <el-form-item label="功能名称" prop="name">
          <el-input v-model="searchEntity.name" placeholder="功能名称"> </el-input>
        </el-form-item>

        <!-- <el-form-item label="类别" prop="type">
          <el-select-v2
            v-model="searchEntity.type"
            :options="[
              { value: '菜单', label: '菜单' },
              { value: '功能', label: '功能' }
            ]"
            placeholder="类别"
          ></el-select-v2>
        </el-form-item> -->

        <el-form-item label="所属父类" prop="parentNo">
          <el-tree-select
            v-model="searchEntity.parentNo"
            :data="treeList.tree.list"
            check-strictly
            :render-after-expand="false"
            placeholder="所属父类"
            style="width: 180px"
          ></el-tree-select>
        </el-form-item>

        <el-form-item label="权限" prop="permission">
          <el-input v-model="searchEntity.permission" placeholder="权限"> </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="enable">
          <el-select-v2
            v-model="searchEntity.enable"
            :options="[
              { value: 1, label: '启用' },
              { value: 0, label: '停用' }
            ]"
            placeholder="状态"
          >
          </el-select-v2>
        </el-form-item>
      </div>

      <el-row style="justify-content: center">
        <el-button type="primary" auto-insert-space icon="Search" @click="getPage">搜索</el-button>
        <el-button auto-insert-space icon="CircleClose" @click="resetForm">重置</el-button>
        <el-button type="primary" link @click="showMore"
          >{{ more.text
          }}<el-icon class="el-icon--right"><component :is="more.icon"></component></el-icon
        ></el-button>
      </el-row>
    </el-form>
  </el-card>

  <div class="dataTable">
    <el-row class="tableBtn">
      <!-- <el-button-group class="ml-4"> -->
      <el-button
        type="primary"
        icon="CirclePlus"
        auto-insert-space
        @click="handleEdit(null)"
        v-has="'menu:add'"
        >新增</el-button
      >

      <el-button
        type="danger"
        icon="Delete"
        auto-insert-space
        :disabled="!selected.length"
        @click="batchDelete"
        v-has="'menu:del'"
        >删除</el-button
      >

      <el-text type="warning" style="margin-left: 2em"
        >温馨提醒：该功能请在开发人员的指引下使用，请勿随意修改参数数据，以免造成系统无法使用！</el-text
      >

      <!-- <el-button type="warning" icon="Download" auto-insert-space>导出</el-button> -->
      <!-- </el-button-group> -->
    </el-row>
    <el-row>
      <el-table
        :data="tableData.records"
        border
        stripe
        max-height="550"
        size="small"
        row-key="no"
        fit
        @selection-change="selectionChange"
        :header-cell-style="tableHeaderStyle"
        show-overflow-tooltip
      >
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center">
          <template #default="scope">
            <span v-text="scope.row.index"></span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="功能名称" width="150" align="center"></el-table-column>

        <el-table-column prop="type" label="类别" width="75" align="center">
          <!-- <template #default="scope">
            <span v-if="scope.row.type == 0">菜单</span>
            <span v-if="scope.row.type == 1">功能</span>
          </template> -->
        </el-table-column>

        <el-table-column prop="icon" label="图标" width="50" align="center">
          <template #default="scope">
            <el-icon size="1.3em" style="vertical-align: text-top">
              <component :is="scope.row.icon"></component>
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column prop="url" label="地址" width="150"></el-table-column>

        <el-table-column prop="parentName" label="所属父类" width="150"></el-table-column>

        <el-table-column prop="permission" label="权限" width="150"></el-table-column>

        <el-table-column
          prop="sort"
          label="顺序"
          width="80"
          align="center"
          sortable
        ></el-table-column>

        <el-table-column prop="enable" label="状态" width="75" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              active-text="启用"
              inactive-text="停用"
              @click="updateEnable(scope.row, scope.row.no, scope.row.enable)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column
          prop="createTime"
          label="添加时间"
          width="130"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column width="250" align="center" v-has="['menu:edit', 'menu:del', 'menu:add']"  fixed="right">
          <template #header>操作</template>
          <template #default="scope">
            <el-button
              size="small"
              icon="Edit"
              type="primary"
              @click="handleEdit(scope.row.no)"
              v-has="'menu:edit'"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="handleDelete(scope.row.no)"
              v-has="'menu:del'"
              >删除</el-button
            >
            <el-button
              v-if="scope.row.type == '菜单'"
              size="small"
              icon="CirclePlus"
              type="success"
              @click="handleAddGongNeng(scope.row.no)"
              v-has="'menu:add'"
              >功能</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="dataTablePage">
      <el-pagination
        background
        :current-page="tableData.current"
        :page-size="tableData.size"
        :default-page-size="10"
        :page-sizes="[10, 20, 30, 40]"
        layout="sizes, prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-row>
  </div>

  <edit-form ref="editfrom" @getPage="getPage"></edit-form>
</template>
<style scoped lang="scss"></style>
